package com.giantlizard.cloud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.giantlizard.cloud.base.constants.CacheConstants;
import com.giantlizard.cloud.redis.utils.RedisOperator;
import com.giantlizard.cloud.system.entity.SysDict;
import com.giantlizard.cloud.system.mapper.SysDictMapper;
import com.giantlizard.cloud.system.service.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统-字典 服务实现类
 */
@Service
@Slf4j
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    private final RedisOperator redisOperator;


    public SysDictServiceImpl(RedisOperator redisOperator) {
        this.redisOperator = redisOperator;
    }

    @Override
    public void refreshDict(String distName) {
        List<SysDict> list = this.list(new LambdaQueryWrapper<SysDict>().eq(SysDict::getDictName, distName));
        if (!list.isEmpty()) {
            redisOperator.delKey(CacheConstants.DICT_PREFIX + distName);
            redisOperator.setObj(CacheConstants.DICT_PREFIX + distName, list);
        }
    }

    @Override
    public void updateDict(SysDict sysDict) {
        this.update(sysDict, new QueryWrapper<SysDict>().eq("id", sysDict.getId()));
        refreshDict(sysDict.getDictName());
    }

    @Override
    public void refreshAllDict() {
        deleteKeysWithPrefix();
        List<SysDict> list = this.list();
        if (list != null && !list.isEmpty()) {
            Map<String, List<SysDict>> map = list.stream()
                    .collect(Collectors.groupingBy(SysDict::getDictName));
            map.forEach((key, value) -> redisOperator.setObj(CacheConstants.DICT_PREFIX + key, value));
        }
    }

    public void deleteKeysWithPrefix() {
        Set<String> keys = redisOperator.keys(CacheConstants.DICT_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisOperator.delKeys(keys);
        }
    }
}


